<template>
  <div>
    <router-view>
      <div class="box">
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>医生管理</span>
            </div>
            <div style="height: 2vh"></div>
            <div class="header">
              <div class="left">
                <el-input
                  style="width: 150px; margin-right: 20px"
                  @input="searchDepart"
                  v-model="departvalue"
                  placeholder="输入科室"
                />
                <el-input
                  style="width: 150px; margin-right: 20px"
                  @input="searchDepart"
                  v-model="doctorvalue"
                  placeholder="输入医生"
                />
                <!-- <el-button type="primary" @click="searchDepart()">搜索</el-button> -->
              </div>
              <div class="right">
                <el-button type="danger" @click="deleteBatches">批量删除</el-button>
                <el-button type="primary" @click="addOffice">新增医生</el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            ref="table"
            :data="pageData"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            stripe="true"
            @select-all="clickSelectAll"
            @select="rowSelect"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
            max-height="68vh"
          >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="name" label="医生姓名" width="100" fixed="left" />
            <el-table-column prop="heat" label="头像" width="140">
              <template #default="scope">
                <img class="head_img" :src="url + scope.row.avatar" alt="" />
              </template>
            </el-table-column>
            <el-table-column prop="duties" label="职称" width="120" />
            <el-table-column prop="depart_name" label="科室" width="120" />
            <el-table-column prop="num" label="标签" width="120">
              <template #default="scope">
                <div style="display: flex; justify-content: center">
                  <div
                    class="lable"
                    :style="{
                      color: scope.row.lable_style.color,
                      backgroundColor: scope.row.lable_style.back,
                    }"
                    >{{ scope.row.lable_style.name }}</div
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="good" label="擅长">
              <template #default="scope">
                <div class="single-line-overflow">{{ scope.row.good }}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="num" label="医生介绍">
            <template #default="scope">
              <div class="list_word" v-html="scope.row.content"></div>
            </template>
          </el-table-column> -->
            <el-table-column prop="create_time" label="创建时间" width="130" />
            <el-table-column label="操作" width="140" fixed="right">
              <!-- <template #default="scope">
              <img
                style="width: 20px; height: 20px; margin-right: 10px"
                src="../../assets/编辑.png"
                alt=""
                @click="handleEdit(scope.$index, scope.row)"
              />
              <img
                style="width: 20px; height: 20px"
                src="../../assets/删除-01.png"
                alt=""
                @click="handleDelete(scope.$index, scope.row)"
              />
            </template> -->
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: center">
            <el-pagination
              style="padding: 10px"
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 30]"
              layout="total, sizes,->, prev, pager, next, jumper"
              :total="listNum"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
      <!-- 新增/编辑页面 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="form.id <= 0 ? '新增标签信息' : '编辑标签信息'"
        @close="cancel()"
        width="50%"
      >
        <div class="window">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="医生名称" prop="name">
              <el-input v-model="form.name" placeholder="输入医生名称" />
            </el-form-item>
            <el-form-item label="性别" prop="sex" style="display: flex; align-items: center">
              <el-radio-group v-model="form.sex">
                <el-radio label="1" size="large">男</el-radio>
                <el-radio label="2" size="large">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="医生头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :action="url + 'pc/Fileimg/file'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="uploadError"
              >
                <img v-if="form.avatar" :src="url + form.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="挂号费" prop="money">
              <el-input v-model="form.money" placeholder="输入挂号费" />
            </el-form-item>
            <el-form-item label="所属医院" prop="status">
              <div class="form_word">{{ hospitalData.data[0].name }}</div>
              <div class="form_word">状态</div>
              <el-switch v-model="form.status" />
            </el-form-item>
            <el-form-item label="所属科室" prop="depart_id">
              <el-select v-model="form.depart_id" clearable placeholder="请选择科室">
                <el-option
                  v-for="item in departList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="医生职称" prop="duties">
              <el-input v-model="form.duties" placeholder="输入医生职称" />
            </el-form-item>
            <el-form-item label="医生标签" prop="tar_id">
              <el-select v-model="form.tar_id" clearable placeholder="请选择标签">
                <el-option
                  v-for="item in lablelist"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="医生擅长" prop="good">
              <el-input type="textarea" :rows="2" v-model="form.good" placeholder="输入医生擅长" />
            </el-form-item>
            <el-form-item label="医生介绍" prop="content">
              <vue-ueditor-wrap
                style="width: 680px; z-index: 1"
                v-model="form.content"
                :config="editorConfig"
              ></vue-ueditor-wrap>
            </el-form-item>

            <div style="direction: rtl">
              <el-form-item>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0"
                  >新增</el-button
                >
                <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
                <div style="width: 10px"></div>
                <el-button @click="cancel(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </router-view>
  </div>
</template>

<script setup>
  import { ref, watchEffect, onMounted, reactive } from 'vue';
  import { depart, addDoctor, doctor, lable, hospital, deleteDoctor } from '../../api/doctor';
  import { Plus } from '@element-plus/icons-vue';
  const form = reactive({
    depart_id: '', //科室ID
    name: '', //医生名称
    good: '', //擅长
    money: '', //挂号费
    duties: '', //职称
    content: '', //介绍
    sex: '', //性别·
    avatar: '', //头像
    tar_id: '', //标签id
    id: '', //编辑医生id
    status: true, //状态
  });
  // UEditor配置
  const editorConfig = reactive({
    autoHeightEnabled: false,
    initialFrameHeight: 200,
    initialFrameWidth: '100%',
    UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
    serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
    uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
    // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
  });
  const dialogFormVisible = ref(false); //弹窗状态
  const url = ref('https://lxt.jingyi.icu/'); //域名头
  const switchvalue = ref(false);
  const listNum = ref(0); //列表总数
  const currentPage = ref(1); //当前页码数
  const pageSize = ref(10); //当前每页显示数量
  const loading = ref(true); //加载状态
  const ruleFormRef = ref(); //页面表单实例
  const status = ref(true); //编辑添加页的显示隐藏状态
  const table = ref(); //表格实例
  const doctorList = ref([]); //医生列表
  const departList = ref([]); //科室列表
  const lablelist = ref(); //标签列表
  const departvalue = ref(''); //搜索框内容
  const doctorvalue = ref(''); //搜索框内容
  const searchData = ref([]); //搜索后列表
  const hospitalData = ref();
  const handleAvatarSuccess = (response, uploadFile) => {
    console.log(response);
    console.log(uploadFile);
    form.avatar = response.data.url;
  };
  const uploadError = (error, uploadFile) => {
    console.log(error);
    console.log(uploadFile);
    form.avatar = response.data.url;
  };
  // 表单效验
  const rules = reactive({
    depart_id: [
      {
        required: true,
        message: '请选择科室',
        trigger: 'change',
      },
    ],
    name: [
      {
        required: true,
        message: '请输入医生名称',
        trigger: 'change',
      },
    ],
    good: [
      {
        required: true,
        message: '请输入医生擅长',
        trigger: 'change',
      },
    ],
    money: [
      {
        required: true,
        message: '请输入挂号费',
        trigger: 'change',
      },
    ],
    duties: [
      {
        required: true,
        message: '请输入职称',
        trigger: 'change',
      },
    ],
    content: [
      {
        required: true,
        message: '请输入医生介绍',
        trigger: 'change',
      },
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
        trigger: 'change',
      },
    ],
    avatar: [
      {
        required: true,
        message: '请上传头像',
        trigger: 'change',
      },
    ],
    tar_id: [
      {
        required: true,
        message: '请选择标签',
        trigger: 'change',
      },
    ],
  });
  //分页数据显示
  const pageData = computed(() => {
    console.log();
    let a = [];
    for (
      let i = (currentPage.value - 1) * pageSize.value;
      i < currentPage.value * pageSize.value;
      i++
    ) {
      if (searchData.value[i]) {
        a.push(searchData.value[i]);
      }
    }
    console.log(a);
    return a;
  });
  // 搜索
  const searchDepart = () => {
    searchData.value = doctorList.value.filter(function (item) {
      if (
        item.depart_name.indexOf(departvalue.value) > -1 &&
        item.name.indexOf(doctorvalue.value) > -1
      ) {
        return item;
      }
    });
    listNum.value = searchData.value.length;
  };
  // 请求列表
  const requestList = async () => {
    try {
      const res = await doctor();
      const ress = await depart();
      const lables = await lable();
      lablelist.value = lables.data;
      hospitalData.value = await hospital();
      for (let i = 0; i < res.data.length; i++) {
        for (let j = 0; j < ress.data.length; j++) {
          if (res.data[i].depart_id == ress.data[j].id) {
            res.data[i].depart_name = ress.data[j].name;
          }
        }
        for (let k = 0; k < lables.data.length; k++) {
          if (res.data[i].tar_id == lables.data[k].id) {
            res.data[i].lable_style = lables.data[k];
          }
        }
      }
      //科室选择只选子集
      let data = [];
      for (let i = 0; i < ress.data.length; i++) {
        if (ress.data[i].pid != 0) {
          data.push(ress.data[i]);
        }
      }
      departList.value = data;
      doctorList.value = res.data;
      searchDepart();
      loading.value = false;
      console.log('初次列表', searchData.value);
    } catch (error) {
      console.error(error);
    }
  };
  requestList();
  // 每页显示数量改变
  const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    console.log(`${val} items per page`);
  };
  // 页码数改变
  const handleCurrentChange = (val) => {
    currentPage.value = val;
    console.log(`current page: ${val}`);
  };
  // 编辑
  const handleEdit = (index, row) => {
    dialogFormVisible.value = true;
    clearForm();

    form.id = row.id;
    form.name = row.name;
    form.avatar = row.avatar;
    form.content = row.content;
    form.depart_id = row.depart_id;
    form.duties = row.duties;
    form.good = row.good;
    form.status = row.status == 0 ? false : true;
    form.money = row.money;
    form.sex = String(row.sex);
    form.tar_id = parseInt(row.tar_id);
    console.log(form);
    console.log(index, row);
  };
  // 删除
  const handleDelete = (index, row) => {
    console.log(index, row);
    ElMessageBox.confirm('是否确认删除?', '删除医生', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then((res) => {
        console.log(res);

        deleteDoctor({
          id: row.id,
        }).then((result) => {
          console.log(result);
          if (result.code == 0) {
            ElMessage({
              type: 'danger',
              message: result.msg,
            });
          } else if (result.code == 1) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            requestList();
          }
        });
      })
      .catch((res) => {
        console.log(res);
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  };
  // 批量删除
  const deleteBatches = () => {
    let arr = table.value.getSelectionRows();
    if (arr.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择需要删除的数据',
      });
    } else {
      ElMessageBox.confirm('是否确认删除?', '删除医生', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then((res) => {
          console.log(res);
          let arr = table.value.getSelectionRows();
          let arrs = [];
          console.log(arr);
          // 构造一个 Promise 数组，每个 Promise 表示一条记录的删除操作
          const promises = arr.map((element) => {
            return deleteDoctor({ id: element.id });
          });
          // 使用 Promise.all() 处理 Promise 数组，一旦其中有一个Promise被拒绝（即删除失败），就会执行catch()方法，
          // 否则，如果所有的Promise都得到了解决（即删除成功），就会执行then()方法。
          Promise.all(promises)
            .then((results) => {
              console.log(results);
              results.forEach((result) => {
                if (result.code == 0) {
                  ElMessage({
                    type: 'danger',
                    message: result.msg,
                  });
                } else if (result.code == 1) {
                  arrs.push(result.data);
                }
              });
              if (arrs.length == arr.length) {
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                });
              } else {
                ElMessage({
                  type: 'warning',
                  message: '删除失败，请重试',
                });
              }
              requestList();
            })
            .catch((error) => {
              console.log(error);
              ElMessage({
                type: 'warning',
                message: '删除失败，请重试',
              });
            });
        })
        .catch((res) => {
          console.log(res);
          ElMessage({
            type: 'info',
            message: '取消删除',
          });
        });
    }
  };
  // const deleteBatches = () => {
  //   ElMessageBox.confirm('是否确认删除?', '删除医生', {
  //     confirmButtonText: '确认',
  //     cancelButtonText: '取消',
  //     type: 'warning',
  //   })
  //     .then((res) => {

  //     })
  //     .catch((res) => {
  //       console.log(res);
  //       ElMessage({
  //         type: 'info',
  //         message: '取消删除',
  //       });
  //     });
  // };
  // 清空表单
  const clearForm = () => {
    form.depart_id = '';
    form.name = '';
    form.good = '';
    form.money = '';
    form.duties = '';
    form.content = '';
    form.sex = '';
    form.avatar = '';
    form.tar_id = '';
    form.id = '';
    form.status = true;
  };
  // 新增
  const addOffice = () => {
    form.id = '';
    // clearForm();
    dialogFormVisible.value = true;
    ruleFormRef.value.clearValidate();
  };
  // 取消
  const cancel = (formEl) => {
    clearForm();
    ruleFormRef.value.clearValidate();
    dialogFormVisible.value = false;
  };
  // 确认新增/编辑科室
  const affirm = async (formEl) => {
    console.log(form);
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        addDoctor(form).then((res) => {
          console.log(res);
          if (res.code == 1) {
            ElMessage({
              type: 'success',
              message: `${res.msg}`,
            });
            dialogFormVisible.value = false;
          } else {
            ElMessage({
              type: 'error',
              message: '操作失败',
            });
          }
          cancel();
          requestList();
        });
        console.log('submit!');
      } else {
        console.log('error submit!', fields);
      }
    });
  };
</script>

<style lang="scss" scoped>
  .box {
    width: 100%;
    background-color: rgb(255, 255, 255);
    overflow-y: scroll;
  }

  .header {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .head_word {
    width: 100%;
    padding: 10px 20px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 20px;
    color: #427eff;
  }

  .window {
    width: 100%;
    // overflow-x: scroll;
    padding: 10px;
    background-color: white;
  }

  .hint {
    margin-left: 10px;
    color: #a6a6a6;
    font-size: 14px;
  }

  .single-line-overflow {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .head_img {
    width: 40px;
    height: 40px;
    border-radius: 40px;
  }

  .lable {
    width: 80%;
    line-height: 1;
    border-radius: 8px;
    padding: 3px;
    padding-top: 5px;
    padding-bottom: 5px;
  }

  .list_word {
    width: 100%;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .inpuut_box {
    width: 800px;
    display: flex;
    flex-wrap: wrap;
  }

  // .box_top {
  //   width: 400px;
  // }

  .box_bottom {
    width: 750px;
  }

  //上传
  .avatar-uploader {
    border: 1px dashed var(--el-border-color) !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    display: flex;
    align-items: center;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  //上传
  .form_word {
    margin-right: 20px;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
